import React, { PureComponent } from 'react';
import style from './index.less';
import { connect, routerRedux } from 'dva';
import { Spin } from 'antd';
import { NoQueryC, PrimaryC } from '../../../comps';
import OneItemC from './myComps/oneItemC';
import AddPortfolioC from './myComps/addPortfolio';
import { isZiGuanEvir } from '../../../utils/commonFunc';

class CollectingMonitoring extends PureComponent {
  state = {
    dataSource: undefined, //卡片列表
    visible: false, //新增编辑弹窗是否可见
    productId: undefined, //当前产品id
    timeOutGap: 10000,
    isStop: false, //暂停
    loadingStatus: true, //加载状态
  };
  componentDidMount() {
    this.queryProuctList(); //查询卡片列表
    if (!isZiGuanEvir()) return; //资管环境下 处理当前tab还是非当前
    //监听postMessage消息事件
    const onmessage = (e) => {
      //监听iframe里maat
      let obj = e.data;
      if (typeof obj == 'object' && obj.nowKey !== undefined) {
        if (obj.nowKey == true && !this.timer && !this.state.isStop) {
          console.log('ziguan set');
          this.setTimer(); //设置定时器
        } else if (obj.nowKey == false) {
          console.log('ziguan clear');
          //离开前清除掉定时器
          if (this.timer) this.clearTimer();
        }
      }
    };
    if (typeof window.addEventListener != 'undefined') {
      window.addEventListener('message', onmessage, false);
    } else if (typeof window.attachEvent != 'undefined') {
      window.attachEvent('onmessage', onmessage);
    }
  }
  componentWillUnmount() {
    //离开前清除掉定时器
    console.log('离开');
    this.clearTimer();
  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    if (nextProps.nowKey == true && !this.timer && !this.state.isStop) {
      console.log('set');
      this.setTimer(); //设置定时器
    } else if (nextProps.nowKey == false) {
      //离开前清除掉定时器
      if (this.timer) this.clearTimer();
    }
  }

  //设置定时器
  setTimer = () => {
    this.timer = setInterval(() => {
      //每5s请求一次
      this.queryProuctList();
    }, this.state.timeOutGap);
  };
  //清除定时器
  clearTimer = () => {
    this.timer && clearInterval(this.timer);
    this.timer = null;
  };
  //查询卡片列表
  queryProuctList = () => {
    this.props.dispatch({
      type: 'CollectingMonitoringM/queryProuctList',
      payload: {
        due: 1,
      },
      callback: (data) => {
        if (data) {
          this.setState({
            dataSource: data.dataSource || [],
          });
          if (this.state.loadingStatus) {
            this.setState({
              loadingStatus: false,
            });
          }
        }
      },
    });
  };
  //跳转到组合跟踪页面
  goToTrack = (id, item) => {
    if (!item) return;
    let searchInfo = {
      productId: id,
      isSimulate: item.isSimulate,
      title: item.productName,
    };
    sessionStorage.setItem('searchInfo', JSON.stringify(searchInfo));
    if (isZiGuanEvir()) {
      //资管平台 跳转处理
      // 通知iframe 更新或者打开详情页iframe
      window.parent.postMessage(searchInfo, '*'); //抛出事件，将数据转成字符串避免一些浏览器不兼容
      return;
    }
    this.props.dispatch(routerRedux.push(`/portfolioBuild/portfolioTracking`));
  };
  //新建或者编辑模拟组合
  addOrEdit = (id) => {
    //清除掉定时器
    this.clearTimer();
    this.setState({
      isStop: true,
    });
    if (id) {
      //编辑需要id
      this.setState(
        {
          productId: id,
        },
        () => {
          this.setState({
            visible: true,
          });
        },
      );
    } else {
      this.setState(
        {
          productId: undefined,
        },
        () => {
          this.setState({
            visible: true,
          });
        },
      );
    }
  };
  //删除卡片
  delCardById = (id) => {
    //清除掉定时器
    this.clearTimer();
    this.setState({
      isStop: true,
    });
    this.props.dispatch({
      type: 'CollectingMonitoringM/deleteById',
      payload: {
        productId: id,
      },
      callback: () => {
        //删除成功刷新页面 自动触发了componentWillprops 这里就不再设置定时器
        this.queryProuctList();
        this.setState({
          isStop: false,
        });
      },
    });
  };
  //弹窗关闭
  onCancel = (args) => {
    if (args == 'ok') {
      //保存成功 刷新页面
      this.queryProuctList();
    }
    this.setState({
      //关闭弹窗
      visible: false,
    });
    this.setState({
      isStop: false,
    });
    this.setTimer(); //进行刷新
  };
  render() {
    const { dataSource, loadingStatus } = this.state;
    return (
      <div style={{ overflow: 'hidden' }}>
        <PrimaryC title='新建模拟组合' onClick={() => this.addOrEdit()} style={{ marginBottom: '20px', marginTop: '8px' }} />
        <Spin spinning={loadingStatus}>{loadingStatus && <div style={{ height: 'calc(100vh - 200px' }}></div>}</Spin>
        {dataSource && dataSource.length ? (
          <div style={{ overflow: 'hidden', marginRight: '-20px' }}>
            {dataSource.map((item, key) => {
              return (
                <OneItemC
                  data={item}
                  onClick={(e) => {
                    this.goToTrack(e, item);
                  }}
                  onEdit={(e) => {
                    this.addOrEdit(e);
                  }}
                  onDelete={(e) => {
                    this.delCardById(e);
                  }}
                  key={key}
                />
              );
            })}
          </div>
        ) : null}
        {dataSource && !dataSource.length && !loadingStatus && <NoQueryC title='当前无产品数据和模拟组合数据' />}

        {this.state.visible && <AddPortfolioC id={this.state.productId} onCancel={(e) => this.onCancel(e)} visible={this.state.visible} />}
      </div>
    );
  }
}
export default connect(({ CollectingMonitoringM, userM: user, loading }) => ({
  CollectingMonitoringM,
  user,
  loading,
}))(CollectingMonitoring);
